# -*- coding: UTF-8 -*-
from datetime import datetime

from django.http.response import HttpResponse
from django.shortcuts import render_to_response
from django.template import loader
from django.template.base import Template
from django.template.context import Context

from orm.models import Entity


def view(request, strs, digital):
    html = "hello world ! %s %d" % (strs, int(digital));
    return HttpResponse(html);

def vhtml(request, p):
    now = datetime.now();
    if (p == 't'):
        t = loader.get_template("t/t.html");
        context = Context({'val':"value"});
        return HttpResponse(t.render(context));
    if (p == 'c'):
        for index in range(5):
            db = Entity();
            db.key = "key_" + str(index);
            db.val = "value_" + str(index);
            db.save(); #saveOrUpdate
        return render_to_response("t/t.html", locals());#render_t0_response是对get_template的简单封装
    if (p == "u"):
        db = Entity();
        db.id = 1;
        db.key = "u";
        db.save();
        return render_to_response("t/t.html", locals());
    if (p == "g"):
        db = Entity.objects.get(id=1);
        return render_to_response("t/db.html", locals());
    if (p == "l"):  # criteria
        '''
        __contains = $args                   =>    like %args%
        __gt[gte,lt,lte,ne] = $args          =>     >  args
        __exact                              =>     not in args;exclude args
        order_by(-{0,1}column)[offset,limit]
        '''
        list = Entity.objects.filter(key__contains="key").order_by("-id")[0:2];
        return render_to_response("t/db.html", locals());
    if (p == "e"):  # 复杂的查询可以使用extra方法
        list = Entity.objects.extra(where=['id > %s'], params=['1']);  
        return render_to_response("t/db.html", locals());
    if (p == "d"):
        db = Entity.objects.get(id=5);
        db.delete();
        return render_to_response("t/t.html", locals());
    
#     原生态查询SQL
#     raw_sql = "select * from tb_entity";
#     raw_qr = Entity.objects.raw(raw_sql);
#     for obj in raw_qr:
#         print obj
    
    # default
    t = Template("<html><body>It is now : {{now}} </body></html>");
    c = Context({"now":now});
    html = t.render(c);
    return HttpResponse(html);
        
    
